<template>
  <basic-container class="app-found">
    <el-col style="background: #fff;padding: 20px 50px">
      <el-col>
        <div class="else-message">下单仓库与配送地址</div>
        <el-form ref="listMessage" :inline="true" :model="listMessage" :rules="rules" class="demo-form-inline" style="display: block">
          <el-col style="display: flex; height: 60px;">
            <el-form-item label="下单仓库" label-width="120px" required class="commonForm" style="width: 70%;display: flex;margin-bottom: 1px!important;">
              <el-form-item prop="deptId" style="width: 25%">
                <el-select v-model="listMessage.deptId" clearable  filterable placeholder="城市" size="medium" style="width: 100%;" @change="cityclick">
                  <el-option v-for="(house,citykey) in cityselect" :key="citykey" :label="house.deptName" :value="house.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="mainWarehouseId" style="width: 25%">
                <el-select v-model="listMessage.mainWarehouseId" placeholder="总仓" size="medium" style="width: 100%;margin-left: 5px;" @change="onMainWarehouseChange">
                  <el-option v-for="(house,ware) in citylist" :key="ware" :label="house.deptName" :value="house.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="warehouseId" style="width: 25%">
                <el-select v-model="listMessage.warehouseId" placeholder="分仓" @change="getwarehouseId" size="medium" style="width: 100%;margin-left: 5px;">
                  <el-option v-for="(house,ware) in abbrlist" :key="ware" :label="house.name" :value="house.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 06:23 添加的区块 -->
              <el-form-item>
                <el-popover
                  class="warehouse"
                  placement="right-end"
                  width="200"
                  v-model="isWarehouse"
                  trigger="click">
                  <el-select
                    v-model="warehouseValue"
                    placeholder="请选择仓库"
                    @change="getwarehouseValue"
                    filterable
                  >
                    <el-option-group
                      v-for="group in options"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-option-group>
                  </el-select>
                  <el-button slot="reference" @click="onWarehouseGroup">选择仓库</el-button>
                </el-popover>

              </el-form-item>
              <!-- 分割线 -->
            </el-form-item>
          </el-col>
          <el-col>
            <div style="position: relative" class="getadressDetailDiv">
              <el-form-item label="定位" label-width="115px" style="margin-top: -6px;">
                <el-input
                  type="textarea"
                  id="getDetail"
                  v-model.trim="listMessage.address1"
                  maxlength="54"
                  @focus="SearchAddress(); addressFlag = true"
                  @input="SearchAddress"
                  @keyup.up.native="selectTopItem()"
                  @keyup.down.native="selectBottomItem()"
                  @keydown.enter.native="getlnglat(currentIndex)"
                  autocomplete="off"
                  placeholder="请输入地址"
                  size="medium"
                  autosize
                  show-word-limit
                  style="width: 530px;"
                ></el-input>
              </el-form-item>
              <!-- v-if="addressFlag" -->
              <div
                id='mapDiv'
                class="adressDetailDiv">
                <ul
                  v-show="addressFlag || isaddressFlag"
                  id='mapDiv'
                  class="adressDetail"
                >
                  <li
                    v-for="(addressitem,index) in addressList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                    :key="index"
                    :class="currentIndex == index ? 'addressActive' : ''"
                    id='mapDiv'
                    @mouseover="changeColor(index)"
                    @mouseout="loseColor(index)"
                    @click="getlnglat(index)"
                  >
                    <!-- @mouseover="changeColor($event)" -->
                    <!-- @mouseout="loseColor($event)" -->
                    <p id='mapDiv' class="el-icon-location-information">{{ addressitem.name }}</p>
                    <p id='mapDiv' class="el-icon-location-information">地址：<span v-if="addressitem.address.length > 0 ? true : false">{{ addressitem.address }}</span></p>
                    <p id='mapDiv' class="el-icon-location-information">城市：<span v-if="addressitem.district !== ''? true : false">{{ addressitem.district }}</span></p>
                  </li>
                  <el-pagination
                    id='mapDiv'
                    background
                    :current-page.sync="currentPage"
                    layout="prev, pager, next, sizes, total, jumper"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size.sync="pagesize"
                    :total="addressList.length"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    style="margin-top: 5px 0;"
                  >
                  </el-pagination>
                </ul>
              </div>
            </div>
            <el-form-item label="地址" label-width="115px" prop="address2">
              <el-input
                type="textarea"
                v-model.trim="listMessage.address2"
                placeholder="请输入楼层、房号"
                maxlength="54"
                show-word-limit
                autosize
                size="medium"
                style="width: 530px;"
              ></el-input>
            </el-form-item>
            <div>
              <el-form-item label="坐标" label-width="115px" prop="longAndLat">
                <el-input
                  v-model.trim="listMessage.longAndLat"
                  placeholder="115.781085,36.111883"
                  size="medium"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col>
            <div class="amap-page-container">
              <XmMap ref="xmMap" style="height: 500px; margin: 0;"></XmMap>
            </div>
          </el-col>
          <div class="else-message">商品信息</div>
          <el-col v-if="tableCakeData && tableCakeData.length" style="width: 100%;margin: 0 70px 30px 79px;">
            <ul class="EditCake">
              <li
                v-for="(itemcake,indexcake) in tableCakeData"
                :key="indexcake"
                class="EditCakeLi">
                <p class="EditCakeLine"><span>蛋糕：</span><span>{{ itemcake.goodsName}}</span></p>
                <p class="EditCakeLine"><span>规格：</span><span>{{ itemcake.goodsSpecs }}</span></p>
                <div class="EditCakeLine" style="display: flex;">
                  <div style="width: 30%;"><span>价格：</span><i class="cak">{{ (itemcake.price/100).toFixed(2) }}</i>元</div>
                  <div style="width: 30%;"><span>数量：</span><span>{{ itemcake.num }}</span></div>
                </div>
                <!-- <p class="EditCakeLine"><span>状态：</span><span>{{ itemcake.goodsSpecs }}</span></p> -->
                <p class="EditCakeLine"><span>祝福语：</span><span>{{ itemcake.blessings?itemcake.blessings:'' }}</span></p>
              </li>
            </ul>
            <el-col style="margin: 0 0 30px 119px;">
              <el-button type="primary" @click="openEditCake">编辑蛋糕</el-button>
            </el-col>
          </el-col>
          <el-col v-if="!(tableCakeData && tableCakeData.length)">
            <el-col style="margin: 0 0 10px 119px;line-height: 80px;">
              还没有蛋糕，请点击下面“编辑蛋糕”按钮选择蛋糕
            </el-col>
            <el-col style="margin: 0 0 30px 119px;">
              <el-button type="primary" @click="openEditCake">编辑蛋糕</el-button>
            </el-col>
          </el-col>
          <div class="else-message">其他信息</div>
          <el-col>
            <el-form-item label="订单总价" label-width="130px" prop="totalPrice" style="width: 37%;display: flex;">
              <el-input v-model.trim="listMessage.totalPrice" placeholder="请输入订单总价" oninput="value=value.replace(/[^\d.]/g,'')" maxlength="10" size="medium" style="width: 210px" :disabled="!canEditPay"></el-input>
            </el-form-item>
          </el-col>
          <el-col></el-col>
          <div class="else-message">其他信息</div>
          <el-col style="display: flex;">
            <el-form-item label="收货人" label-width="130px" prop="name" style="width: 37%;display: flex;">
              <el-input v-model.trim="listMessage.name" placeholder="请输入收货人" maxlength="10" size="medium" style="width: 210px"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" label-width="130px" prop="phone" style="width: 37%;display: flex;">
              <el-input v-model.trim="listMessage.phone" placeholder="请输入手机号码" maxlength="11" size="medium" style="width: 210px"></el-input>
            </el-form-item>
          </el-col>
          <el-col style="display: flex;">
            <el-form-item label="下单人" label-width="130px" prop="bookerName" style="width: 37%;display: flex;">
              <el-input v-model.trim="listMessage.bookerName" placeholder="请输入下单人" maxlength="10" size="medium" style="width: 210px"></el-input>
            </el-form-item>
            <el-form-item label="下单人手机号码" label-width="130px" prop="bookerPhone" style="width: 37%;display: flex;">
              <el-input v-model.trim="listMessage.bookerPhone" placeholder="请输入手机号码" maxlength="11" size="medium" style="width: 210px"></el-input>
            </el-form-item>
          </el-col>
          <el-col style="display: flex;">
            <el-form-item label="渠道类别" label-width="130px" prop="channelType" style="width: 37%;display: flex;" class="commonForm">
              <el-select v-model="listMessage.channelType" @keydown.native="channelFilter" clearable filterable placeholder="请选择渠道类别" size="medium" style="width: 210px">
                <el-option v-for="(channelitem,channel) in channelTypellist" :key="channel" :label="channelitem.channelName" :value="channelitem.channelKey">
                  <span :data-id="channelitem.id" style="display: block;width: 100%;padding: 0 20px;margin-left: -20px;" @click="getchannelTypeId($event)">{{ channelitem.channelName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="渠道" label-width="130px" prop="channer" style="width: 37%;display: flex;" class="commonForm">
              <el-select v-model="listMessage.channer" @keydown.native="channelFilter" @visible-change="getchannelList" clearable filterable placeholder="请选择渠道" size="medium" style="width: 210px">
                <el-option v-for="(channelitem,channel) in channerllist" :key="channel" :label="channelitem.channelName" :value="channelitem.channelKey"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col style="display: flex;"> -->
          <el-form-item label="平台单号" label-width="130px" class="commonForm" style="width: 37%;display: flex;">
            <el-input
              v-model.trim="listMessage.platformOrderId"
              @input="accountInput"
              placeholder="请输入平台单号"
              type="textarea"
              maxlength="25"
              show-word-limit
              autosize
              size="medium"
              style="width: 210px"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否跳舞" label-width="130px" class="commonForm" style="width: 37%;display: flex;">
            <el-radio v-model="listMessage.isDance" :label="1">跳舞</el-radio>
            <el-radio v-model="listMessage.isDance" :label="0">不跳舞</el-radio>
          </el-form-item>
          <el-form-item label="配送时间" prop="deliveryStartTime" label-width="130px" required class="selectTime" style="display: flex;">
            <el-date-picker
              type="date"
              size="medium"
              placeholder="选择日期"
              v-model="listMessage.deliveryStartTime"
              :picker-options="pickerOptionsStart"
              :clearable="false"
              value-format="yyyy-MM-dd "
              format="yyyy-MM-dd "
              style="width: 100%;"
            ></el-date-picker>
          <div class="line" :span="1" style="margin-right: 10px;">-</div>
            <selecttime
              ref="getdeliveryTime"
              v-bind:OrderStartTime="OrderStartTime"
              v-bind:OrderEndTime="OrderEndTime"
              v-bind:deliveryTime="listMessage.deliveryStartTime"
            ></selecttime>
          </el-form-item>
          <div class="title-timeShow">
            <p v-for="(item,index) in this.wareHouseTime.warehouseDeliveryTimes" :key="index" class="changeColor">
              {{item.deliveryStartTime.substr(0, 5)}}-{{item.deliveryEndTime.substr(0, 5)}}
              需提前{{item.orderAdvanceTime}}分钟下单，
              {{changeDeliveryStartTime(item.deliveryStartTime, item.deliveryEndTime, item.orderAdvanceTime)}}</p>
            <p v-for="(item,index) in this.wareHouseTime.warehouseCloseTimes" :key="index">关闭接单时间:{{changeDeliveryEndTime(item.closeStartTime, item.closeEndTime)}}</p>
          </div>
          <el-form-item label-width="130px" label="订制商品" v-if="showCustomMade" prop="diyCakeName">
            <diyCakeInfo ref="diyCakeInfo" @diyChange="handleDiyChange"></diyCakeInfo>
          </el-form-item>
          <el-form-item label="客服备注" label-width="130px" prop="customerServiceNotes" style="width: 77%;display: flex;">
            <el-input v-model.trim="listMessage.customerServiceNotes" type="textarea" maxlength="50" show-word-limit autosize placeholder="请输入客服备注" size="medium" style="width: 510px;"></el-input>
          </el-form-item>
          <el-form-item label="配送备注" label-width="130px" prop="deliveryRemark" class="commonForm" style="width: 77%;display: flex;">
            <el-input v-model.trim="listMessage.deliveryRemark" type="textarea" maxlength="200" show-word-limit autosize placeholder="请输入配送备注" size="medium" style="width: 510px;"></el-input>
          </el-form-item>
          <el-form-item label="平台门店" label-width="130px" prop="storeInfo" style="width: 77%;display: flex;">
            <el-input v-model.trim="listMessage.storeInfo" type="textarea" maxlength="30" show-word-limit autosize placeholder="请输入门店信息" size="medium" style="width: 510px;"></el-input>
          </el-form-item>
          <el-form-item label="生产备注" label-width="130px" prop="productRemark" class="commonForm" style="width: 77%;display: flex;">
            <el-input v-model.trim="listMessage.productRemark" type="textarea" maxlength="100" show-word-limit autosize placeholder="请输入生产备注" size="medium" style="width: 510px"></el-input>
          </el-form-item>
          <el-form-item label="客户备注" label-width="130px" prop="customerRemark" style="width: 77%;display: flex;">
            <el-input v-model.trim="listMessage.customerRemark" type="textarea" maxlength="50" show-word-limit autosize placeholder="请输入客户备注" size="medium" style="width: 510px"></el-input>
          </el-form-item>
          <el-col style="display: flex;justify-content: center;">
            <el-button  type="primary" @click="onSubclick('listMessage')" :disabled="foundOrderFlag == true ? true : false" style="margin-right: 20px;">立即创建</el-button>
            <!-- <el-button @click="cancelOrder('listMessage')">取消订单</el-button> -->
          </el-col>
        </el-form>
      </el-col>
    </el-col>

    <!------------- 编辑商品 --------------  -->
    <editGoodsDialog ref="editGoodsDialog" :ruleForm="listMessage" @onGoodsSubmit="handleGoodsSumbit" :canEditNum="true" :isReserveId="true"></editGoodsDialog>
  </basic-container>
</template>
<script>
import {
  shopList,
  citySelect,
  createOrder,
  getMainWarehouseList,   // 总仓接口
  getSeparateWarehouseList,  // 分仓接口
  getOrderChannelList,// 渠道
  getWarehousesByDeptIds,
  getWarehouseName, // 根据经度纬度，返回分仓总仓名称
  getProvisionsGoodsPage, // 备款商品分页列表
  createOrderByProvisions, // 创建订单添加备款商品后，判断是否更新原订单状态
  judgeGoodsClose, // 判断当前商品是否关闭
  getSurplusWarehouseLoadList, // 仓库剩余负荷列表
  getOrderChannelTypeList, // 渠道类别列表
  getCloseAndDeliveryList, // 提取关闭接单时间
} from "@/api/createOrder";
import { getWarehouseByType } from "@/api/warehouse";
import { shopSize,getWarehouseListByCityId } from "@/api/pending";
import { getWarehouseList } from "@/api/warehouse";
import deliveryTime from '@/components/foundorder/deliverytime';
import Pagination from "@/components/Pagination"; // 分页
import selecttime from "@/components/foundorder/selecttime"; // 配送时间组件
import axios from 'axios'
import { getWarehouseLabel, inputTipThrottle } from '@/util/map'
import editGoodsDialog from '@/components/order-detail/components/editGoodsDialog'
import diyCakeInfo from '@/components/order/diyCakeInfo'
import { mapGetters } from "vuex";

export default {
  components: {
    deliveryTime,
    Pagination,
    selecttime,
    editGoodsDialog,
    diyCakeInfo,
  },
  data() {
    var validPhone = (rule, value, callback) => {
      const reg = /^1[0-9][0-9]\d{8}$/;
      if(!value) {
        callback(new Error('请输入电话号码'));
      } else if(!reg.test(value)) {
        callback(new Error('请输入正确的电话号码'));
      } else {
        callback();
      }
    };
    var validNorequiredPhone = (rule, value, callback) => {
      const reg = /^1[0-9][0-9]\d{8}$/;
      if(!value) {
        callback();
        return
      } 
      if(!reg.test(value)) {
        callback(new Error('请输入正确的电话号码'));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入地址'));
      } else {
        this.listMessage.address2 = value.replace(/\s+/g, '');
        callback();
      }
    };
    var checkData = (rule, value, callback) => {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          this.listMessage.totalPrice = '';
          callback(new Error('编码不能输入汉字!'));
        } else {
          callback();
        }
      }
      callback();
    };
    // 校验定制信息
    let validateDiyData = (rule, value, callback) => {
      if (this.showCustomMade) {
        const diyData = this.$refs.diyCakeInfo.getDiyData()
        if (!diyData.diyCakeName) {
          callback(new Error("请填写订制商品名称!"));
        }
        if (diyData.diyCakeNum + 0 <= 0) {
          callback(new Error("请填写订制商品数量!"));
        }
        if (
          (diyData.diyCakeName == "定制米数蛋糕" ||
          diyData.diyCakeName == "定制多层蛋糕") &&
         (!diyData.diyCakeMeter)  
        ) {
          callback(new Error("请填写订制商品规格!"));
        }
        callback()
      }
    }
    let validateDeliveryTime = (rule, value, callback) => {
      console.log(this)
      if (this.listMessage.deliveryStartTime && this.$refs.getdeliveryTime  && this.$refs.getdeliveryTime.getEndTime()) {
        callback()
      } else {
        callback(new Error("请选择配送日期及时间!"));
      }
    }
    return {
      wareHouseTime: [],  // 获取时间列表
      options: [],   // 操作合并数组
      warehouseValue: '', // 操作内容
      isWarehouse: false, // 显示摁钮弹框

      deptId:'',
      // 创建订单请求表单
      listMessage: {
        receiverAddress: "西湖区骆家庄西苑一区",
        channel: 1,
        name: '',
        phone: '',
        warehouseId: '',
        platformOrderId: '',
        deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
        channelType: '',// 渠道类别
        channer: '',// 渠道
        // deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
        customerNotes: "帮我祝他快乐",
        productionNotes: "",
        deliveryNotes: "",
        longAndLat: '',
        longitude: '',
        deliveryStartTime: "",
        deliveryEndTime: "",
        address1: '',
        address2: '',
        totalPrice: 0,
        startTime: '',
        endTime: '',
        checkOrder: '',
        mainWarehouseId: '',
        customerServiceNotes: '', // 客服备注
        storeInfo: '', // 门店信息
        deliveryRemark: '',// 配送备注
        productRemark: '',// 生产备注
        customerRemark: '',// 客户备注
        isDance: 1,
        bookerName: '',
        bookerPhone: '',
      },
      // form表单
      rules: {
        name: [{
          required: true,
          message: "请输入收货人",
          trigger: "change"
        }],
        phone: [
          { required: true, validator: validPhone, trigger: 'change' }
        ],
        bookerPhone: [
          { required: false, validator: validNorequiredPhone, trigger: 'change' }
        ],
        totalPrice: [
          { required: true, message: "请输入订单总价", trigger: 'blur' },
          { validator: checkData, trigger: 'change'}
        ],
        channer: [{ required: true, message: "请输入渠道", trigger: "change" }],
        deliveryStartTime: [
          { required: true, validator: validateDeliveryTime, trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        deptId: [
          { required: true,
            message: '请选择仓库',
            trigger: 'change'
          }
        ],
        mainWarehouseId: [
          { required: true, message: "请选择总仓", trigger: "change" }
        ],
        warehouseId: [{ required: true, message: "请选择分仓", trigger: "change" }],
        address2: [
          {
            required: true,
            validator: validatePass,
            trigger: 'change'
          }
        ],
        diyCakeName: [
          { required: true, validator: validateDiyData, trigger: "blur" },
        ],
        channelType: [{ required: true, message: "请选择渠道类别", trigger: "change" }],
        customerServiceNotes: [{ required: false, message: '请输入客服备注', trigger: 'change' }],
        deliveryRemark: [{ required: false, message: '请输入配送备注', trigger: 'change' }],
        storeInfo: [{ required: false, message: '请输入门店信息', trigger: 'change' }],
        productRemark: [{ required: false, message: '请输入生产备注', trigger: 'change' }],
        customerRemark: [{ required: false, message: '请输入客户备注', trigger: 'change' }]
      },
      currentIndex: '', // 地图列表激活
      pickerOptionsStart: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      cityselect: "", // 城市获取列表
      citylist: "", // 下单仓库中的总仓
      abbrlist: "", // 分仓
      channelTypellist: '', // 渠道类别列表
      channerllist: "", // 渠道列表
      addressFlag: false, // 地址详情列表的显隐
      isaddressFlag: false, // 地址详情列表的显隐
      addressList: '', // 地址详情列表
      pagesize: 5, // 分页
      currentPage: 1, // 分页
      getWarehouseName: {  // 根据经度纬度，返回分仓总仓名称
        longitude: 1,
        latitude: 2
      },
      tableCakeData: [],// 点击提交后显示的蛋糕
      cityId: '',
      getChannelList: { // 渠道列表
        parentId: ''
      },
      OrderStartTime: '',
      OrderEndTime: '',
      foundOrderFlag: false, // 创建订单按钮点击置灰
      map: '',//地图
    }
  },
  created(){
  },
  mounted() {
    this.listMessage.deptId = JSON.parse(window.localStorage.getItem("saber-areaId")).content;
    // 未点击城市时划区域  处理经纬度坐标
    setTimeout(() => {
      this.handleMapData()
    })
    citySelect({roleId: 1}).then(res => {
      this.cityselect = res.data.data;
    })
    this.getMainWarehouseList()
    // 渠道类别列表
    getOrderChannelTypeList().then(res => {
      this.channelTypellist = res.data.data;
    })
    let _this = this;
    // 点击页面空白处
    document.onclick = function(event) {
      var $event = event || window.event;
      let targetId = $event.target.id;
      let parentId = $event.target.parentElement.parentElement.id;
      if($event.target.parentElement.parentElement.parentElement !== null) {
        let parentParentId = $event.target.parentElement.parentElement.parentElement.id;
        // 不等于当前点点击的名字
        if((targetId !== 'getDetail') && (targetId !== 'mapDiv') && (parentId !== 'mapDiv') && (parentParentId !== 'mapDiv')) {
          _this.addressFlag = _this.isaddressFlag = false;
        }
      }
    }
  },
  watch: {
    'listMessage.warehouseId'(value){
      if (value) {
        getCloseAndDeliveryList({'wid':value}).then(res=>{
          this.wareHouseTime = res.data.data
        })
      }
    },
    'listMessage.channelType'() {
      if(this.listMessage.channelType == null || this.listMessage.channelType == '')  this.listMessage.channer = this.getChannelList.parentId = '';
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    // 私人订制
    showCustomMade() {
      return this.tableCakeData && this.tableCakeData.some((item) =>
        item.goodsName.includes("私人订制")
      );
    },
    canEditPay() {
      return this.permission['detail_edit_pay']
    },
  },
  methods: {
    changeDeliveryEndTime(startTime,endTime){
      return `${startTime}~${endTime}`
    },
    changeDeliveryStartTime(startTime, endTime, orderAdvanceTime){
      var myDate=new Date()
      myDate = new Date(myDate.getTime() + orderAdvanceTime * 60 * 1000);

      var endDateTime = new Date();
      if(endTime === '00:00:00') {
        endDateTime.setHours(23);
        endDateTime.setMinutes(59);
      } else {
        endDateTime.setHours(endTime.substr(0,2) * 1);
        endDateTime.setMinutes(endTime.substr(3,2) * 1);
      }
      if(myDate.getTime() > endDateTime.getTime()) {
        return '不建议选择当天配送'
      }

      return '当天配送建议选择配送时间：'
        + `${myDate.getHours() > 9? myDate.getHours(): `0${myDate.getHours()}`}:${myDate.getMinutes()>9 ? myDate.getMinutes(): `0${myDate.getMinutes()}`} - `
        + endTime.substr(0, 5);
    },
    // 三仓 赋值事件
    getwarehouseValue(e){
      this.isWarehouse = false
      let name = e
      this.options.map((item,index)=>{
        item.options.map( (item,index)=>{
          if(item.value == this.warehouseValue){
            
            this.listMessage.mainWarehouseId = item.id    // 城市ID
            getSeparateWarehouseList({'deptId':item.id}).then(res=>{
              let result = res.data.data
              this.abbrlist = result;
              result.map((item,index)=>{
                if(e == item.name){
                  this.listMessage.parentId = item.deptId
                  this.listMessage.warehouseId = item.id
                }
              })
            })
          }
        })
      })
      this.warehouseValue = ''
    },
    // 渠道类型空格过滤
    channelFilter(e) {
      if(e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getchannelTypeId(e){
      if(e.currentTarget.dataset.id !== ''){
        this.getChannelList.parentId = e.currentTarget.dataset.id
        getOrderChannelList(this.getChannelList).then(res => {
          let result = res.data.data
          result.forEach(item => {
            this.channerllist = result;
            if(this.listMessage.channer !== undefined) {
              if (item.channelKey == this.listMessage.channer) {
                this.channerllist = result;
              } else {
                this.channerllist = result;
                this.listMessage.channer = ''
              }
            }
          })
        })
      }
    },
    getchannelList() {
      // 渠道列表接口
      if(this.getChannelList.parentId !== '') {
        getOrderChannelList(this.getChannelList).then(res => {
          this.channerllist = res.data.data;
        })
      } else {
        this.$message.warning('请先选择渠道类别');
        this.channerllist = '';
      }
    },
    // 地图事件
    SearchAddress() {
      if(this.listMessage.address1 !== '') {
        const citySelected = this.cityselect.find(item => this.listMessage.deptId == item.id)
        inputTipThrottle({
          city: citySelected.deptName,
          keyword: this.listMessage.address1
        }).then(res => {
          this.addressList = res.sort((a, b) => {
            return a.district.includes(citySelected.deptName) && !b.district.includes(citySelected.deptName) ? -1 : 0
          })
        })
      }
    },
    // 点击地图的列表获取经纬度
    getlnglat(index) {
      index = (this.currentPage - 1) * this.pagesize + index;
      let _this = this;
      if((typeof index) === 'string') index = 0;
      this.addressFlag = false;
      this.isaddressFlag = false;
      if(this.addressList[index].location !== undefined && this.addressList[index].location.lat !== undefined) {
        this.addressList[index].lat = this.addressList[index].location.lat;
        this.addressList[index].lng = this.addressList[index].location.lng;
      }
      let pois = this.addressList[index];
      this.currentIndex = index;
      if(pois.lat !== undefined) {
        this.listMessage.latitude = pois.lat
        this.listMessage.longitude = pois.lng
        this.getWarehouseName.latitude = pois.lat
        this.getWarehouseName.longitude = pois.lng
        getWarehouseName(this.getWarehouseName).then(res => {
          // console.log('res',res.data.data)
          if(res.data.msg === '操作成功') {
            // console.log('在配送区域内',res.data.data)
            this.listMessage.deptId = res.data.data.cityId;
            this.listMessage.address1 = pois.name;
            this.listMessage.mainWarehouseId = res.data.data.deptId;
            this.listMessage.warehouseId = res.data.data.id;
            this.handleMapData()

            if((typeof res.data.data.deptId) === 'number') {
              getSeparateWarehouseList({deptId: res.data.data.deptId}).then(res => {
                this.abbrlist = res.data.data
              })
            }
            this.getMainWarehouseList()
            // console.log('this.addressList[index]999',this.addressFlag,this.isaddressFlag)
          } else if (res.data.msg == '暂无承载数据') {
            this.$confirm('您选择的地址不在配送范围内, 请到下单仓库中选择城市！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.listMessage.address1 = pois.name;
              this.handleMapData()
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消选择地址'
              })
            })
          }
          // console.log('res.data.data',res.data.data)
        })
      } else {
        this.$confirm('此地址不存在, 请重新选址！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '请继续选择地址!'
          });
          // this.listMessage.address1 = ''
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消选择地址'
          });
        });
      }
    },
    //方向键（向上）
    selectTopItem () {
      if(this.addressList.length > 0 && this.addressList.length <= 5) {
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex--;
        } else {
          this.currentIndex = 0;
        }
        // console.log('上',this.currentIndex)
      } else {
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex--;
        } else {
          this.currentIndex = 0;
        }
      }
    },
    //方向键（向下）
    selectBottomItem (index) {
      if(this.addressList.length > 0 && this.addressList.length <= 5) {
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex++;
        } else {
          this.currentIndex = 0;
        }
      } else {
        // console.log('2',this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1)
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex++;
        } else {
          this.currentIndex = 0;
        }
      }
    },

    //  平台单号
    accountInput(val){//账号的实时输入
      //console.log(val);
      let codeReg = new RegExp("[A-Za-z0-9]+"), //正则 英文+数字；
        len=val.length,
        str='';
      for(var i=0;i<len;i++){
        if(codeReg.test(val[i])){
          str+=val[i];
        }
      }
      // console.log(str)
      this.listMessage.platformOrderId=str;
    },
    // 划过列表颜色改变
    changeColor(index) {
      this.currentIndex = index
      // e.currentTarget.style.background = '#F5F7FA'
    },
    // 离开列表颜色改变
    loseColor(index) {
      this.currentIndex = index
      // e.currentTarget.style.background = '#fff'
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pagesize = size
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    

    // 下单仓库城市获取
    cityclick(value) {
      this.listMessage.mainWarehouseId = ''
      this.listMessage.warehouseId = ''

      const listMessage = this.cityselect.find(item => item.id == value)
      if(listMessage){
        this.getMainWarehouseList()
        this.handleMapData()
      }
    },
    getMainWarehouseList() {
      getMainWarehouseList({parentId: this.listMessage.deptId}).then(res => {
        let result = res.data.data
        this.citylist = result;
      })
    },
    // 创建订单并获取后台单号
    onSubclick(formName) {
      this.foundOrderFlag = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.tableCakeData || !this.tableCakeData.length) {
            this.$confirm('你还未添加商品，请添加商品！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).finally(() => {
              this.foundOrderFlag = false;
            })
            return
          }
          if((this.listMessage.latitude !== '' && this.listMessage.longitude !== '') || this.listMessage.longAndLat !== '') {
            const orderParams = this.getParams()
            createOrder(orderParams).then(res => {
              if(res.data.code == 200) {
                const xmbzNo = res.data.data.data && res.data.data.data.xmbzNo
                const workOrderProvisionsList = this.tableCakeData.filter(item => item.workOrderProvisionsIds && item.workOrderProvisionsIds.length)
                if (workOrderProvisionsList && workOrderProvisionsList.length) {
                  // 如有备款蛋糕
                  workOrderProvisionsList.forEach(item => {
                    item.newXmbzNo = xmbzNo
                  })
                  createOrderByProvisions({ 'workOrderProvisionsList': this.workOrderProvisionsList }).then(res => {
                    if (res.data.code == 200) {
                      this.$alert(`下单成功！后台单号：${xmbzNo}`, '提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                          this.$message({
                            type: 'success',
                            message: `操作成功`
                          });
                          this.$refs[formName].resetFields()
                          this.delCreateOrder();
                        }
                      })
                    }
                    this.$refs[formName].resetFields()
                    this.delCreateOrder();
                  })
                } else {
                  this.$alert(`下单成功！后台单号：${xmbzNo}`, '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                      this.$message({
                        type: 'success',
                        message: `操作成功`
                      });
                      this.$refs[formName].resetFields()
                      this.delCreateOrder();
                    }
                  })
                }
              } else {
                this.$message({
                  type: 'warning',
                  message: `${res.data.msg}`
                })
              }
            }).catch(error => {
            }).finally(() => {
              this.foundOrderFlag = false;
            })
          } else {
            this.$message.warning('定位获取失败，请再次尝试!');
            this.foundOrderFlag = false;
          }
        } else {
          this.$confirm('还有信息未填完整，请补充完整?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$message({
              type: 'success',
              message: '请完善信息!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消创建订单'
            });
          }).finally(() => {
            this.foundOrderFlag = false;
          });
          return false;
        }
      })
    },
    getParams() {
      const branchWarehouseSelected = this.abbrlist.find(item => item.id == this.listMessage.warehouseId)
      const mainWarehouseSelected = this.citylist.find(item => item.id == this.listMessage.mainWarehouseId)
      const params = {
        deliveryStartTime: `${(this.listMessage.deliveryStartTime).trim()} ${(this.$refs.getdeliveryTime.getStartTime()).trim()}`,
        deliveryEndTime: `${(this.listMessage.deliveryStartTime).trim()} ${(this.$refs.getdeliveryTime.getEndTime()).trim()}`,
        receiverAddress: this.listMessage.address2,
        receiverName: this.listMessage.name,
        receiverPhone: this.listMessage.phone,
        platformOrderId: this.listMessage.platformOrderId,
        channelType: this.listMessage.channelType,
        channel: this.listMessage.channer,
        branchWarehouse: branchWarehouseSelected.name,
        warehouseId: this.listMessage.warehouseId,
        mainWarehouse: mainWarehouseSelected.deptName,
        mainWarehouseId: this.listMessage.mainWarehouseId,
        deptId: this.listMessage.deptId,
        customerNotes: this.listMessage.customerRemark,
        productionNotes: this.listMessage.productRemark,
        deliveryNotes: this.listMessage.deliveryRemark,
        customerServiceNotes: this.listMessage.customerServiceNotes,
        storeInfo: this.listMessage.storeInfo,
        totalPrice: this.listMessage.totalPrice * 100,
        isDance: this.listMessage.isDance,
        bookerName: this.listMessage.bookerName,
        bookerPhone: this.listMessage.bookerPhone,
        latitude: this.listMessage.latitude,
        longitude: this.listMessage.longitude,
        orderDetailList: this.tableCakeData.filter(item => {
          return ['配件', '服务费', '定制蛋糕', '增值服务'].every(name => name != item.goodsTypeName && !(item.workOrderProvisionsIds && item.workOrderProvisionsIds.length))
        }),
        serviceClassList: this.tableCakeData.filter(item => item.goodsTypeName == '服务费'),
        partsList: this.tableCakeData.filter(item => item.goodsTypeName == '配件' || item.goodsTypeName == '增值服务'),
        workOrderProvisionsList: this.tableCakeData.filter(item => item.workOrderProvisionsIds && item.workOrderProvisionsIds.length),
        customizedOrderDetailList: this.tableCakeData.filter(item => item.goodsTypeName == '定制蛋糕'),
      }
      if (this.showCustomMade) {
        const diyData = this.$refs.diyCakeInfo.getDiyData()
        params.diyCakeName = diyData.diyCakeName
        params.diyCakeNum = diyData.diyCakeNum
        params.diyCakeMeter = diyData.diyCakeMeter
      }
      if (this.listMessage.longAndLat) {
        const location = this.listMessage.longAndLat.split(',')
        params.longitude = location[0]
        params.latitude = location[1]
      }
      return params
    },
    // 创建订单后（清空表单）
    delCreateOrder() {
      this.listMessage.thirdOrder = ''
      this.listMessage.address1 = ''
      this.listMessage.totalPrice = 0;
      this.tableCakeData = [] //
      this.listMessage.address2 = '' //
      this.listMessage.latitude = '';
      this.listMessage.longitude = '';
      this.$refs.getdeliveryTime.StartTime = '';
      this.$refs.getdeliveryTime.EndTime = '';
      this.listMessage.platformOrderId = '';
      this.foundOrderFlag = false;
    },
    // 获取分仓id
    getwarehouseId(val) {
    },
    // 定制信息blur
    handleDiyChange(diyInfo) {
      this.listMessage.productRemark = this.listMessage.productRemark.replace(/【订制信息：([\s\S]+)】/, '') + `【订制信息：${diyInfo}】`
    },
    // 选择总仓
    onMainWarehouseChange() {
      this.listMessage.warehouseId = ''
      if (this.listMessage.mainWarehouseId) {
        getSeparateWarehouseList({deptId: this.listMessage.mainWarehouseId}).then(res => {
          this.abbrlist = res.data.data
        })
      } else {
        this.abbrlist = []
      }
    },
    // 查询总仓对应分仓
    onWarehouseGroup() {
      this.options = this.citylist.map((item) => {
        return {
          ...item,
          label: item.deptName,
          options: [],
        }
      })
      if (this.options && this.options.length) {
        axios.all(this.options.map((item) => {
          return getSeparateWarehouseList({'deptId':item.id})
        })).then(resList => {
          this.options.forEach((item, index) => {
            const res = resList[index]
            item.options = res.data.data.map(($0,index)=>{
              return {
                cityId: $0.cityId,
                id: $0.deptId,
                value: $0.name,
              }
            })
          })
        })
      }
    },
    // 处理地图元素
    async handleMapData() {
      if (this.$refs.xmMap) {
        this.$refs.xmMap.clearMap()
        if (this.listMessage.deptId) {
          await this.addWarehouseOnMap();
          await this.addPlatformWarehouseOnMap();
        }
        if (this.listMessage.longitude && this.listMessage.latitude) {
          this.addLocationMarkerOnMap();
          this.$refs.xmMap.setCenter([this.listMessage.longitude, this.listMessage.latitude])
        } else {
          this.$refs.xmMap.map.setFitView()
        }
      }
    },
    // 添加当前位置
    addLocationMarkerOnMap() {
      const marker = this.$refs.xmMap.createMarker({
        longitude: this.listMessage.longitude,
        latitude: this.listMessage.latitude,
        label: {
          content: `<div class='info'>${this.listMessage.address1}</div>`
        },
        icon: {
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
        },
        zIndex: 50
      })
      this.$refs.xmMap.map.add([marker])
    },
    // 添加当前分仓边界
    async addWarehouseOnMap() {
      await getWarehouseList({ cityId: this.listMessage.deptId }).then(res => {
        const resData = res.data.data || [];
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#000",
            strokeWeight: 3,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#fff",
            zIndex: 40,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
    },
    // 添加当前中央厨房
    async addPlatformWarehouseOnMap() {
      await getWarehouseByType({
        cityId: this.listMessage.deptId,
        type: 99,
      }).then(res => {
        const resData = res.data.data || []
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#FF33FF",
            strokeWeight: 2,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
    },
    openEditCake() {
      if (!this.listMessage.warehouseId) {
        this.$message({
          message: "您还未选择仓库，请选择仓库后再添加蛋糕",
          type: "warning",
        });
        return
      }
      this.$refs.editGoodsDialog.show({shoplist: this.tableCakeData})
    },
    // 蛋糕提交
    handleGoodsSumbit({shoplist, sumPrice}) {
      this.tableCakeData = shoplist || [];
      this.listMessage.totalPrice = (sumPrice / 100).toFixed(2);
    },
  }
};
</script>
<style lang="scss" scoped>
#panel {
  position: absolute;
  background-color: white;
  max-height: 260px;
  overflow-y: auto;
  top: 8px;
  right: 10px;
  width: 280px;
  opacity: .9;
}
/*---------- 蛋糕已选表格 ----------*/
.fund-order-table {
  border-collapse: collapse;
  text-align: center;
}
.fund-order-table tr {
  border: 1px solid rgb(223, 228, 237);
}
.fund-order-table tr td {
  border: 1px solid rgb(223, 228, 237);
  padding: 0.5rem 0.5rem;
  height: 2.6rem;
  line-height: 1rem;
}
.el-scrollbar {
  padding-bottom: 15px;
}
</style>
<style lang="scss">
p{
  margin: 0;
  padding: 0;
}
.title-timeShow{
  margin-left: 60px;
  font-size: 14px;
  color: #ef4136;
  .changeColor{
    color: darkorange;
  }
  p{
    margin: 0;
    padding: 0;
    line-height: 30px;
  }
}
.warehouse{
  .el-button{
    margin-left: 10px;
    padding: 10px;
    font-size: 12px;
  }
}
.Num-input{
  width: 80px;
  margin: 0 10px;
  input{
    padding-left: 10px;
  }
}
.page-component__scroll .el-scrollbar__wrap {
  overflow-x: hidden;
}
.app-found {
  min-height: calc(100vh - 50px);
  overflow: hidden;
}
.amap {
  height: 600px;
  margin: 0 10px 10px 10px;
}
.else-message {
  margin: 0 0 15px 37px;
  font-size: 20px;
  font-weight: 600;
}
.line {
  color: #C0C4CC;
  font-weight: 600;
}
/****      地图搜索下拉地址   */
.getadressDetailDiv .adressDetailDiv {
  width: 600px;
  background: #fff;
  position: absolute;
  top: 35px;
  left: 118.68px;
  z-index: 99;
}
.adressDetail {
  margin: 0;
  padding: 0;
  list-style: none;
  border: 1px solid #DCDFE6;
  // width: 300px;
}
.adressDetail li {
  border-bottom: 1px solid #DCDFE6;
  // background: #fff;
}
.adressDetail li p{
  margin: 0;
  padding: 0 10px;
  list-style: none;
  width: 280px;
  text-align: left;
  line-height: 1.6;
}
// .adressDetail li.hover {
//   background-color: #F5F7FA;
// }
.adressDetail li p:first-child {
  font-size: 17px;
}
.adressDetail li p:last-child {
  color: #999;
}
.addressActive {
  // background-color: #000;
  background: #F5F7FA;
}
.EditCakeLi {
  padding: 15px;
  width: 80%;
  list-style: none;
  background:#efefef;
  margin-bottom: 15px;
  p{
    line-height: 60px;
  }
}
.EditCakeLine {
  font-size: 17px;
  font-weight: 550;
}
/*---------- 添加蛋糕样式 -----------*/

.order-message {
  margin-top: 2%;
  // border-bottom: 0.1rem solid #dfe4ed;
  padding-bottom: 2%;
  margin-bottom: 5px;
}
.order-list {
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  font-family: Helvetica Neue, Arial, PingFang SC, microsoft yahei, STXihei;
  color: #3f4156;
  box-sizing: inherit;
  margin-top: 10px;
  margin: 0.5rem;
  box-shadow: rgb(223, 228, 237) 2px 2px 10px;
}
.order-list .order-list-item {
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  font-family: Helvetica Neue, Arial, PingFang SC, microsoft yahei, STXihei;
  color: #3f4156;
  box-sizing: inherit;
  margin-bottom: 20px;
  border-bottom: 1px solid #fff;
  background: #fff;
}
.order-user-area {
  padding: 10px 20px;
}
.orderfound-header-area .order-header {
  position: relative;
  // height: 50px;
  overflow: hidden;
}
.orderfound-header-area .order-header .order-num {
  display: inline-block;
  position: relative;
  // height: 33px;
  background: #585a6e;
  color: #fff;
  padding: 0 10px;
  text-align: left;
  display: flex;
  align-items: center;
  // margin-top: 10px;
}
.orderfound-header-area .order-header .order-time {
  margin-left: 30px;
}
.orderfound-header-area .order-header .order-num span {
  position: relative;
  z-index: 9;
  font-size: 16px;
  // line-height: 2;
}
.orderfound-header-area .order-header .order-num i {
  display: block;
  position: absolute;
  right: -9px;
  top: 7px;
  width: 18px;
  height: 19px;
  background: #585a6e;
  -webkit-transform: rotate(55deg) skewX(25deg);
  transform: rotate(55deg) skewX(25deg);
  z-index: 0;
}
.order-user-area .user-phone-address .phone-title {
  color: #858692;
}
.price-style {
  color: red;
  margin-right: 5px;
}
.app-container .amap-marker-label .info {
  margin-bottom: 0px;
}
.app-container .amap-marker-label {
  font-size: 12px;
  border: 1px solid blue;
  line-height: 14px;
}
.app-found {
  .el-col .el-form-item {
    margin-bottom: 20px!important;
  }
}
.selectTimesubmit {
  display: flex;
  justify-content: center;
  margin-top: -30px;
  margin-left: 50px;
}
.el-form-item__content .el-textarea .el-input__count {
  line-height: 10px;
}
// 去掉输入框textarea的斜杠
.el-form-item .el-form-item__content .el-textarea.el-input--medium textarea {
  resize: none;
}
.selectTime {
  .el-form-item__content {
    display: flex;
  }
}
// 在填充数据之前隐藏
[v-cloak] {
  display: none;
}
</style>
